﻿using BaseUI;
using BLL;
using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.PublicShow
{
    public partial class SelectUser : BasePage
    {
        private Sys_CompanyBLL scb = new Sys_CompanyBLL();
        private Sys_UserBLL sub = new Sys_UserBLL();
        private Sys_DepartmentBLL sdb = new Sys_DepartmentBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request["mode"]))
                {
                    string nems = Request["mode"].ToString();
                    string SelectType = (Request["mode"].ToString() == "1" ? "单选" : "多选");
                }
            }
        }

        private void BindCompanyByWhere(ref string name, ref string cid)
        {
            DataTable dt = scb.GetAllInfo(" AND CMY_PARENTID=0");

            foreach (DataRow dr in dt.Rows)
            {
                name = dr["CMY_NAME"].ToString();
                cid = dr["CMY_ID"].ToString();
                string unit = "【" + "总公司" + "】";
                TreeNode t = new TreeNode(name + unit, cid);
                MyTree.Nodes.Add(t);
                LoadComNode(Convert.ToInt32(cid), t);
                MyTree.ExpandDepth = 1;
            }
        }

        //获取公司节点的递归方法
        private void LoadComNode(int parent, TreeNode pNode)
        {
            DataTable dataDep = sdb.GetDataAllInfo(@"AND d.CMY_ID = " + parent + " AND ( d.DEPTPARENTID = 0 or d.DEPTPARENTID =-1) "); //公司直属部门
            if (dataDep.Rows.Count > 0)
            {
                for (int i = 0; i < dataDep.Rows.Count; i++)
                {
                    string unit = "【" + "部门" + "】";

                    TreeNode node = new TreeNode(dataDep.Rows[i]["DEPTNAME"].ToString() + unit, dataDep.Rows[i]["DEPTID"].ToString());
                    pNode.ChildNodes.Add(node);
                    string whereStr = " AND USER_COMPANY=" + dataDep.Rows[i]["CMY_ID"].ToString() + " AND USER_DEPARTMENT=" + dataDep.Rows[i]["DEPTID"].ToString();
                    whereStr += ViewState["Where"];
                    BindUser(node, whereStr);
                    LoadDepNode(Convert.ToInt32(node.Value), node);
                }
            }

            DataTable dataCom = scb.GetAllInfo("AND CMY_PARENTID=" + parent);
            if (dataCom.Rows.Count > 0)
            {
                for (int i = 0; i < dataCom.Rows.Count; i++)
                {
                    string unit = "【" + "公司" + "】";

                    TreeNode node = new TreeNode(dataCom.Rows[i]["CMY_NAME"].ToString() + unit, dataCom.Rows[i]["CMY_ID"].ToString());
                    pNode.ChildNodes.Add(node);
                    LoadComNode(Convert.ToInt32(node.Value), node);
                }
            }
        }

        //获取部门
        private void LoadDepNode(int parentDid, TreeNode pNode)
        {
            string whereStr = @" AND d.DEPTPARENTID = " + parentDid;
            whereStr += ViewState["Where"];
            DataTable dataDep = sdb.getDepartMentAndUser(whereStr);
            if (dataDep.Rows.Count > 0)
            {
                for (int i = 0; i < dataDep.Rows.Count; i++)
                {
                    string unit = "【" + "部门" + "】";

                    TreeNode node = new TreeNode(dataDep.Rows[i]["DEPTNAME"].ToString() + unit, dataDep.Rows[i]["DEPTID"].ToString());
                    pNode.ChildNodes.Add(node);
                    string Where = " AND USER_COMPANY=" + dataDep.Rows[i]["CMY_ID"].ToString() + " AND USER_DEPARTMENT=" + dataDep.Rows[i]["DEPTID"].ToString();
                    Where += ViewState["Where"];
                    BindUser(node, Where);
                    LoadDepNode(Convert.ToInt32(node.Value), node);
                }
            }
        }

        //获取人员
        private void BindUser(TreeNode tn, string whereStr)
        {
            DataTable dataUser = sub.GetAllUser(whereStr); //公司直属部门
            TreeNode tr = null;
            //获取从URL传过来的用户ID（string类型）
            string value = Request.QueryString["IdStr"].ToString();
            string[] arry = value.Split(',');
            if (dataUser != null)
            {
                for (int i = 0; i < dataUser.Rows.Count; i++)
                {
                    tr = new TreeNode();
                    //判断用户Id是否相同，是则选中改用户，否则不选中
                    if (((IList)arry).Contains(dataUser.Rows[i]["USER_ID"].ToString()))
                    {
                        tr.Checked = true;
                        tr.Value = dataUser.Rows[i]["USER_ID"].ToString();
                        tr.Text = dataUser.Rows[i]["USER_NAME"].ToString() + "【人员】";
                    }
                    else
                    {
                        tr.Value = dataUser.Rows[i]["USER_ID"].ToString();
                        tr.Text = dataUser.Rows[i]["USER_NAME"].ToString() + "【人员】";
                    }
                    tn.ChildNodes.Add(tr);
                }
            }
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            MyTree.Nodes.Clear();
            string whereStr = "";
            //  int a = 0;

            if (!string.IsNullOrEmpty(txtName.Text))
            {
                string username = txtName.Text.Trim();
                whereStr += " AND u.USER_NAME LIKE '%" + username + "%'";
                // a++;
            }

            if (!string.IsNullOrEmpty(txtLoginName.Text))
            {
                string LoginName = txtLoginName.Text.Trim();
                whereStr += " AND u.USER_LOGINNAME like '%" + LoginName + "%'";
                //  a++;
            }
            if (DrpSex.SelectedValue != "-1")
            {
                string UserSex = DrpSex.SelectedValue == "0" ? "0" : "1";
                whereStr += " AND u.USER_SEX = " + UserSex;
                //   a++;
            }

            if (!string.IsNullOrEmpty(TxtPhone.Text))
            {
                string UserPhone = TxtPhone.Text.Trim();
                whereStr += " AND u.USER_PHONE = " + UserPhone;
                // a++;
            }

            //if (a < 2)
            //{
            //    MessageBox.Show(Page, "为避免数据过多，用时较长，请至少输入两个查询条件");
            //    return;
            //}
            string name = "";
            string cid = "";

            ViewState["Where"] = whereStr;
            BindCompanyByWhere(ref name, ref cid);
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            TreeNodeCollection tnc = MyTree.CheckedNodes;
            try
            {
                int count = 0;
                string Ids = "";
                string Name = "";
                string SelectType = (Request["mode"] == "1" ? "单选" : "多选");
                foreach (TreeNode item in tnc)
                {
                    if (item.Checked)
                    {
                        bool na0 = item.Text.Contains("【公司】");
                        bool na1 = item.Text.Contains("【部门】");
                        bool na2 = item.Text.Contains("【总公司】");
                        if (na0 != true && na1 != true && na2 != true)
                        {
                            count += 1;
                            Name += (item.Text.Substring(0, item.Text.IndexOf("【")) + ",").Replace("总公司,", "");
                            Ids += item.Value + ",";
                        }
                    }
                }

                if (SelectType == "单选" && count != 1)
                {
                    MessageBox.Show(Page, "请选择一个用户");
                    return;
                }
                if (count <= 0)
                {
                    MessageBox.Show(Page, "请至少选择一个用户");
                    return;
                }

                Name = Ids.Substring(0, +Ids.LastIndexOf(',')) + "%" + Name.Substring(0, Name.LastIndexOf(','));
                MessageBox.ResponseScript(this, "FORM_SUBMIT(\"" + Name + "\");");
                return;
            }
            catch (Exception exp)
            {
                MessageBox.Show(Page, "【异常：】" + exp.Message.ToString());
                return;
            }
        }
    }
}